package com.hilinos.ftp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hilinos.common.common.ReturnCode;
import com.hilinos.common.util.AssertUtils;
import com.hilinos.common.util.IdUtils;
import com.hilinos.common.util.JwtUtils;
import com.hilinos.ftp.api.qo.UserListQo;
import com.hilinos.ftp.api.vo.UserLoginVo;
import com.hilinos.ftp.mapper.UserMapper;
import com.hilinos.ftp.pojo.UserPojo;
import com.hilinos.ftp.service.UserService;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserPojo> implements UserService {

    @Override
    public UserLoginVo login(String accountId, String password, HttpServletResponse response) {
        UserPojo user = getById(accountId);
        AssertUtils.isNotEmpty(user, ReturnCode.AUTH_USER_NOT_EXIST);
        AssertUtils.isRex(password.equals(user.getUserpassword()), ReturnCode.AUTH_ACCOUNT_PASSWORD_ERROR);

        user.setUserpassword(IdUtils.DEFAULT.gen().toString());
        String token = JwtUtils.generateJWT(user, 30 * 86400);
        response.addCookie(new Cookie("token", token));
        return UserLoginVo.builder()
                .token(token)
                .name(user.getUserid())
                .build();
    }

    @Override
    public Page<UserPojo> userList(UserListQo qo) {
        QueryWrapper<UserPojo> queryWrapper = new QueryWrapper<>();
        Page<UserPojo> page = new Page<>(1, 20);
        if (qo != null) {
            queryWrapper = qo.queryWrapper();
            page = qo.page();
        }
        queryWrapper.lambda().ne(UserPojo::getUserid, "admin");
        return page(page, queryWrapper);
    }

    @Override
    public UserPojo detail(UserPojo user) {
        AssertUtils.isNotEmpty(user, "用户不能为空");
        AssertUtils.isNotEmpty(user.getUserid(), "用户不能为空");
        return getById(user.getUserid());
    }
}
